<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB, Session, Validator, Hash;

class AdminUserController extends Controller
{
    /**
     * Display a listing of the resource.
     *显示管理员列表
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //查询管理员信息
        $users = DB::table("admin_user")
                ->leftJoin("user_group", "admin_user.id", "=", "user_group.uid")
                ->where("admin_user.admin_name", "LIKE", "%".$request->get("keyword")."%")
                ->orWhere("admin_user.admin_nickname", "LIKE", "%".$request->get("keyword")."%")
                ->orderBy("admin_user.id", "DESC")
                ->paginate("8");
//        dd($users);
//        foreach ($users as $user)
//        {
//            var_dump($user);
//        }
//        echo $users->render();
        //获取搜索条件
        $keyword = $request->get("keyword");
        //查询所有分组
        $groups = DB::table("group_rule")->get();
//        dd($groups);
        //显示模板
         return view("admin.admin.index", compact("users", "keyword", "groups"));
//         return view("admin.admin.index", ["users" => $users, "keyword" => $keyword, "groups" => $groups]);
    }

    /**
     * Show the form for creating a new resource.
     *显示管理员添加表单
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //查询所有的分组
        $groups = DB::table("group_rule")->get();
        return view("admin.admin.create",compact("groups"));
    }

    /**
     * Store a newly created resource in storage.
     *存储一个新建的管理员
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->all();
        //验证数据是否符合要求
//        $validator = Validator::make($data, [
//            //用户名不能为空
//           "admin_name" => "required",
//            //昵称不能为空
//           "admin_nickname" => "required",
//            //密码不能为空|长度应为6-15位
//           "admin_pass" => "required|between:6,15",
//            //邮箱不能为空
//            "admin_email" => "required"           
//        ]);
//        
//        //判断结果并输出
//        if ($validator->fails())
//        {
//            return back()->with(["info" => $validator->errors()]);
//        }
        $this->validate($request, [
           "admin_name" => "required|unique:admin_user",
            "admin_nickname" => "required",
            "admin_pass" => "required|between:6,15",
            "admin_email" => "required"
            ],[
            "admin_name.required" => "用户名不能为空",
            "admin_name.unique" => "用户已存在",
            "admin_nickname.required" => "昵称不能为空",
            "admin_pass.required" => "密码不能为空",
            "admin_pass.between" => "密码长度应为6-15位",
            "admin_email.required" => "邮箱不能为空"
        ]);
        //提取数据并重组

        $data = $request->except("_token",'admin_groupid');
        $data['admin_pass'] = Hash::make($data['admin_pass']);
//        dd($data);
        //执行数据创建
       if (false !== $insertId =  DB::table("admin_user")->insertGetId($data))
       {
           //将新增用户 添加到对应的分组里面
           DB::table("user_group")->insert(["uid" => $insertId, "groupid" => $request->get("admin_groupid")]);
//           dd($insetId);
           return redirect("/admin/admin");
       } else 
       {
           return back()->with(["info" => "添加管理员失败"]);
       }
    }
    
    /**
     * Ajax 请求过来 修改管理员对应分组的功能
     */
    public function setGroup(Request $request)
    {
       if (false !== DB::table("user_group")->where("uid", $request->get("uid"))->update(["groupid" => $request->get("groupid")]))
       {
           return response()->json(["status" => 1, "info" => "修改分组成功"]);
       } else
       {
           return response()->json(["status" => 0, "info" => "修改分组失败"]);
       }
    }
    
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
//        return "这是编辑页面";
//        dd($id);
        //查询该用户记录
        $userRec = DB::table("admin_user")->leftJoin("user_group", "admin_user.id", "=", "user_group.uid")->where("admin_user.id", $id)->first();
//        dd($userRec);
        //查询所有的分组
        $groups = DB::table("group_rule")->get();
        //显示模板
        return view("admin.admin.edit", compact("userRec", "groups"));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
//        dd($id);
        //验证数据的有效性
        $this->validate($request, [
//            "admin_name" => "required|unique:admin_user",
            "admin_nickname" => "required",
            "admin_pass" => "between:6,15",
            "admin_email" => "required"
            ],[
//            "admin_name.required" => "用户名不能为空",
//            "admin_name.unique" => "用户已存在",
            "admin_nickname.required" => "昵称不能为空",
            "admin_pass.between" => "密码长度应为6-15位",
            "admin_email.required" => "邮箱不能为空"
        ]);
        //修改用户数据
        $data = $request->except("_token", "_method",'admin_groupid');
        //对密码重新构造
        if (!empty($data["admin_pass"]))
        {
            $data["admin_pass"] = Hash::make($data["admin_pass"]);
        }else 
        {
            unset($data["admin_pass"]);
        }
        if (false !== $affecteRows = DB::table("admin_user")->where("id", $id)->update($data))//返回影响的行数
        {
            if (DB::table("user_group")->where("uid", $id)->first())
            {
                 //修改用户对应的分组
                DB::table("user_group")->where("uid", $id)->update(["groupid" => $request->get("admin_groupid")]);
            } else 
            {
                DB::table("user_group")->insert(["uid" => $id, "groupid" => $request->get("admin_groupid")]);
            }
           return redirect("/admin/admin");
        } else 
        {
            return back();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
//        dd($id);
        //删除该用户记录
          if (false !== DB::table("admin_user")->where("id", $id)->delete())
          {
              //删除用户对应的分组
              DB::table("user_group")->where("uid", $id)->delete();
              return redirect("/tips")->with(["info" => "操作成功", "url" => "/admin/admin"]);
          } else
          {
//              return redirect("/error/100");  
              return redirect("/tips")->with(["info" => "操作失败", "url" => "/admin/admin"]);
          }
    }
}
